<template>
  <div class="my-tag">
    <input
      @blur="isEdit = false"
      @keyup.enter="onSubmit"
      v-focus
      ref="inpRef"
      v-if="isEdit"
      class="input"
      type="text"
      placeholder="输入标签"
      :value="value"
    />
    <div @dblclick="isShow" v-else class="text">{{ value }}</div>
  </div>
</template>

<script>
export default {
  /* 
    1. input和text互斥显示 默认隐藏input 定义变量 v-if v-else
    2. 双击text 显示input  添加双击事件  改变isEdit
       显示input 自动获取焦点  ref获取dom $nextTick更新后获取焦点
    3. 抽离获取焦点 封装成指令 v-focus   
    4. 接收父组件传递的txt 绑定显示 更改内容 回车修改txt
        props接收数据  注册@keyup.enter 触发$emit与父组件通信 并让input失去焦点
 */
  props: {
    value: {
      type: String,
    },
  },
  data() {
    return {
      isEdit: false,
    };
  },
  methods: {
    isShow() {
      this.isEdit = true;
    },
    onSubmit(e) {
      this.$emit("input", e.target.value);
      this.isEdit = false;
    },
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus();
      },
    },
  },
};
</script>

<style lang="less" scoped>
.my-tag {
  cursor: pointer;
  .input {
    appearance: none;
    outline: none;
    border: 1px solid #ccc;
    width: 100px;
    height: 40px;
    box-sizing: border-box;
    padding: 10px;
    color: #666;
    &::placeholder {
      color: #666;
    }
  }
}
</style>